<template>
    <div class="mapDiv">
        <!-- 如果需要点击地图更改地图中心点请td-map添加事件监听 @click="onClick"  -->
        <tdt-map :center="state.center" :zoom="state.zoom" @click="onClick">
            <tdt-control position="topleft">
                <el-select v-model="hotPointID" filterable remote reserve-keyword placeholder="输入地点关键词"
                    :remote-method="searchAddress" :loading="loading" clearable style="width: 380px; margin-bottom: 5px"
                    @change="handleChange">
                    <el-option v-for="(item, index) in options" :key="item.hotPointID" :label="item.name"
                        :value="item.lonlat + ',' + index">
                        <span>{{ item.name }}</span>
                        <span style="font-size: 12px; color: #a8abb2; margin-left: 10px">{{ item.address }}</span>
                    </el-option>
                    <template #loading>
                        <svg class="circular" viewBox="0 0 50 50">
                            <circle class="path" cx="25" cy="25" r="20" fill="none" />
                        </svg>
                    </template>
                </el-select>
            </tdt-control>


            <!-- 点标注 -->
            <tdt-marker v-for="marker in markers" :position="marker.position" :extData="marker"
                @click="openInfowindow"></tdt-marker>

            <!-- 信息窗口 -->
            <tdt-infowindow v-model:target="state.currentMarker.position" :minWidth="150" :offset="[0, -30]">
                <div>
                    <strong>{{ state.currentMarker.title }}</strong>
                    <div>{{ state.currentMarker.position }}</div>
                </div>
            </tdt-infowindow>

            <!-- 文本标注 -->
            <tdt-label :position="state.center" text="Hello World!" :visible="state.visible"></tdt-label>

            <!-- 自定义返回当前位置控件 -->
            <tdt-control position="bottomright">
                <div class="controlStyle" @click.stop="controlClick">
                    <img style="width: 100%; height: 100%" src="@/assets/img/home.jpg" alt="" />
                </div>
            </tdt-control>

        </tdt-map>
    </div>
</template>

<script lang="ts" setup>
import "vue-tianditu/lib/style.css";
import { reactive, ref, onMounted } from "vue";
import { TdtMap } from "vue-tianditu";
import { ElMessage, ElMessageBox } from 'element-plus'

const loadConfig = reactive({
    v: import.meta.env.VITE_MP_VERSION,
    tk: import.meta.env.VITE_MP_KEY
})

const markers = [
    { title: "这是第一个标记点", position: [113.280637, 23.125178] },
    { title: "这是第二个标记点", position: [113.300637, 23.125178] },
    { title: "这是第三个标记点", position: [113.320637, 23.125178] },
    { title: "这是第四个标记点", position: [113.340637, 23.125178] }
];
const state = reactive({
    center: [113.280637, 23.125178],
    zoom: 12,
    currentMarker: markers[0]
});

onMounted(() => {
    getLocation(); // 获取当前经纬度
});

// 获取当前位置信息
const getLocation = () => {
    if (!navigator.geolocation) {
        ElMessage.error("浏览器不支持地理位置服务");
        return;
    }
    navigator.geolocation.getCurrentPosition(
        (position) => {
            console.log('getLocation', position);
            state.center = [position.coords.longitude, position.coords.latitude];
        },
        (err) => {
            ElMessageBox.alert("请开启浏览器/电脑位置服务！");
        }
    );
};

// 地图点击时触发
const onClick = (e) => {
    state.center = [e.lnglat.lng, e.lnglat.lat];
    getTiandituAddress(e.lnglat.lng, e.lnglat.lat);
};
// 天地图逆地址解析
const getTiandituAddress = async (lng, lat) => {
    const response = await fetch(
        `https://api.tianditu.gov.cn/geocoder?postStr={'lon':${lng},'lat':${lat},'ver':1}&tk=${loadConfig.tk}`
    );
    const data = await response.json();
    return data.result;
};

// 自定义控件搜索周边信息
const options = ref([]); // 位置搜索选项
const hotPointID = ref(""); // 搜索选项id
const searchAddress = async (queryString) => {
    if (!queryString) return;
    console.log('自定义控件搜索周边信息');

    const params = {
        postStr: JSON.stringify({
            keyWord: queryString,
            level: '12', // 搜索等级
            queryRadius: '10000',
            pointLonlat: state.center[0] + ',' + state.center[1],
            queryType: '3', // 查询类型 1:普通搜索3:周边搜索服务
            start: 0, // 起始记录
            count: 20, // 每页数量
        }),
        tk: loadConfig.tk,
        type: 'query',
    };
    const response = await fetch(`http://api.tianditu.gov.cn/v2/search?postStr=${encodeURIComponent(params.postStr)}&tk=${loadConfig.tk}&type=${params.type}`);
    const data = await response.json();
    console.log('搜索结果', data.pois);
    options.value = data?.pois || [];

}
// 下拉框发生变化
const handleChange = (val) => {
    console.log("选择的值", val);
    const arr = val.split(",");
    state.center = [arr[0], arr[1]];
}

// 点击自定义控件
const controlClick = () => {
    getLocation();
};

const openInfowindow = ({ extData }) => {
    state.currentMarker = { ...extData };
}
</script>

<style>
.mapDiv {
    width: 100%;
    height: 100vh;
}
</style>